<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" placeholder="请输入聊天内容">
    <button class="send">发送消息</button>
    <button class="close">关闭链接</button>
    <div class="content"></div>
    <script>

        let content = document.querySelector('.content')
        // 创建远程的链接
        let ws = new WebSocket('wss://echo.websocket.org')
        // 连接成功回调函数 open
        ws.onopen = function () {
            content.innerHTML += '<span style="color:red">链接成功</span>'
        }

        // 发送消息
        document.querySelector('.send').onclick = function () {
            let msg = document.querySelector('input').value
            // 发送消息  send()
            ws.send(msg)
            // 渲染页面
            content.innerHTML += '用户发的:' + msg + '<br>'
        }
        // 接收消息 onmessage
        ws.onmessage = function (event) {
            content.innerHTML += '服务器发的:' + event.data + '<br>'
        }
        // 关闭链接  close() 
        document.querySelector('.close').onclick = function () {
            ws.close()
        }
        //  关闭链接成功的回调函数 onclose()
        ws.onclose = function () {
            content.innerHTML += '<span style="color:red">关闭链接成功</span>'
        }



    </script>
</body>

</html>